import ResourceLoader from './base/ResourceLoader'
import BackGround from './runtime/BackGround'
import Land from './runtime/Land'
import Birds from './player/Birds'
import StartButton from './player/StartButton'
import DataStore from './base/DataStore'
import Director from './Director'
import Score from './player/Score'

export default class Main {
  constructor() {
    this.ctx = canvas.getContext('2d')
    const loader = ResourceLoader.create()
    loader.onLoaded(map => this.onResourceFirstLoaded(map))

    this.dataStore = DataStore.getInstance()
    this.director = Director.getInstance()
  }

  onResourceFirstLoaded(map) {
    this.dataStore.ctx = this.ctx
    this.dataStore.res = map

    this.init()
  }

  init() {

    this.director.isGameOver = false

    this.dataStore
        .put('pencils', [])
        .put('background', BackGround)
        .put('land', Land)
        .put('birds', Birds)
        .put('score', Score)
        .put('startButton', StartButton)

    this.registerEvent()

    this.director.createPencil()
    this.director.run()
  }

  registerEvent() {
    wx.onTouchStart(e => {
      if (this.director.isGameOver) {
        console.log('Restart')
        this.init()
      } else {
        this.director.birdsEvent()
      }
    })
  }
}
